package com.baikeyang.app.controller;

import com.baikeyang.common.model.User;
import com.baikeyang.service.user.IUserService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller(value = "testController")
@RequestMapping("/teana")
public class MessageController {

    private final static Logger log = LogManager.getLogger(MessageController.class);

    @Autowired
    private IUserService userService;

    @RequestMapping("")
    public String index(HttpServletRequest request, HttpServletResponse response){
        return "start";
    }

    @RequestMapping(value = "users")
    public List<User> getAllUsers() {
        List<User> users = userService.getUsers();
        return users;
    }

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> uploadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, String> sMap = new HashMap<String, String>();
        try {
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);

                // 得到所有的提交的表单域，也就是formData
                List<FileItem> fileItems = upload.parseRequest(request);

                String id = "";
                String fileName = "";
                // 如果大于1说明是分片处理
                int chunks = 1;
                int chunk = 0;
                long fileSize = 0;
                long lastModiDate = 0;
                String tableName = "";
                FileItem tempFileItem = null;

                for (FileItem fileItem : fileItems) {
                    if (fileItem.getFieldName().equals("id")) {
                        id = fileItem.getString();
                    } else if (fileItem.getFieldName().equals("name")) {
                        fileName = new String(fileItem.getString().getBytes("ISO-8859-1"), "UTF-8");
                    } else if (fileItem.getFieldName().equals("chunks")) {
                        chunks = NumberUtils.toInt(fileItem.getString());
                    } else if (fileItem.getFieldName().equals("chunk")) {
                        chunk = NumberUtils.toInt(fileItem.getString());
                    } else if (fileItem.getFieldName().equals("multiFile")) {
                        tempFileItem = fileItem;
                    } else if (fileItem.getFieldName().equals("fileSize")) {
                        fileSize = NumberUtils.toLong(fileItem.getString());
                    } else if (fileItem.getFieldName().equals("lastModiDate")) {
                        lastModiDate = NumberUtils.toLong(fileItem.getString());
                    } else if (fileItem.getFieldName().equals("tableName")) {
                        tableName = fileItem.getString();
                    }
                }

                System.out.println(tableName);
                String fileSysName = tempFileItem.getName();
                String realname = lastModiDate+fileSysName.substring(fileSysName.lastIndexOf("."));//转化后的文件名
                sMap.put("fileSysName", fileSysName);
                sMap.put("realname", realname);
                //真实上传的地址，是我底层的地址，这里就不多说了
                String realPath = "D:/log";
                realPath = realPath + File.separator + tableName.toUpperCase() + File.separator;
                String filePath = realPath;//文件上传路径

                // 临时目录用来存放所有分片文件
                String tempFileDir = filePath + id + "_" + fileSize;
                File parentFileDir = new File(tempFileDir);
                if (!parentFileDir.exists()) {
                    parentFileDir.mkdirs();
                }
                // 分片处理时，前台会多次调用上传接口，每次都会上传文件的一部分到后台
                File tempPartFile = new File(parentFileDir, realname + "_" + chunk + ".part");
                FileUtils.copyInputStreamToFile(tempFileItem.getInputStream(), tempPartFile);

                // 是否全部上传完成
                // 所有分片都存在才说明整个文件上传完成
                boolean uploadDone = true;
                for (int i = 0; i < chunks; i++) {
                    File partFile = new File(parentFileDir, realname + "_" + i + ".part");
                    if (!partFile.exists()) {
                        uploadDone = false;
                    }
                }
                // 所有分片文件都上传完成
                // 将所有分片文件合并到一个文件中
                if (uploadDone) {
                    // 得到 destTempFile 就是最终的文件
                    File destTempFile = new File(filePath, realname);
                    for (int i = 0; i < chunks; i++) {
                        File partFile = new File(parentFileDir, realname + "_" + i + ".part");
                        FileOutputStream destTempfos = new FileOutputStream(destTempFile, true);
                        //遍历"所有分片文件"到"最终文件"中
                        FileUtils.copyFile(partFile, destTempfos);
                        destTempfos.close();
                    }
                    // 删除临时目录中的分片文件
                    FileUtils.deleteDirectory(parentFileDir);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return sMap;
    }

    @RequestMapping("/start/{name}/{age}")
    public String start(@PathVariable("name") String name, @PathVariable("age") int age) {
        log.error("姓名：" + name + ", 年龄：" + age);
        log.trace("trace message");
        log.debug("debug message");
        log.info("info message");
        log.warn("warn message");
        log.error("error message");
        log.fatal("fatal message");
        System.out.println("Hello World!");
        return "login";
    }

    public static void main(String[] args) {
//        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
//        Object[] arg = new Object[] { "张三",  Calendar.getInstance().getTime() };
//        String msg =  ctx.getMessage("userinfo", arg,Locale.CHINA);
//        System.out.println("Message is ===> "  + msg);


        log.trace("trace message");
        log.debug("debug message");
        log.info("info message");
        log.warn("warn message");
        log.error("error message");
        log.fatal("fatal message");
        System.out.println("Hello World!");
    }

}
